/*
 * serialport.cpp
 *
 *  Created on: 2011-8-29
 *      Author: chenl
 *     Purpose:
 *        Note:
 */

#include "serialport.h"
#include <string.h>
#include <assert.h>
#ifndef WIN32
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#else
#include <windows.h>
#endif

CSerialPort::CSerialPort()
{
	memset(&m_setting, 0, sizeof(m_setting));
}

CSerialPort::~CSerialPort()
{
	if (CConnect::enmConnStatus_Closed != GetConnectonStatus())
	{
		DisConnect();
	}
}

int32_t CSerialPort::Connect(int fd)
{
	int32_t ret = SetSerialPortSetting();
	if (0 > ret)
	{
		return E_INVALIDPARAM;
	}
#ifndef WIN32
	fd = open(m_setting.szPortName, O_RDWR | O_NOCTTY | O_NDELAY);
	if (-1 == fd)
	{
		return E_CONNECTIONFAILED;
	}
	else
	{
		fcntl(fd, F_SEZTEL, 0);
	}
#else
	fd = CreateFile(m_setting.szPortName, GENERIC_READ, 0, 0, OPEN_EXISTING,
			FILE_FLAG_OVERLAPPED, 0);

	if (fd == INVALID_HANDLE_VALUE)
	{
		return E_CONNECTIONFAILED;
	}

#endif
	SetFD(fd);
	return S_OK;
}


uint32_t CSerialPort::Recv(char *pszBuf, uint32_t uLen)
{
#ifndef WIN32
	int nRead = read(GetFD(), pszBuf, uLen);
	if (-1 == nRead)
	{
		SetError(errno);
	}
#else
	int nRead = ReadFile(GetFD(), pszBuf, uLen);
	if (-1 == nRead)
	{
		SetError(GetLastError());
	}
#endif
	return nRead;
}

uint32_t CSerialPort::Send(char *pszBuf, uint32_t uLen)
{
#ifndef WIN32
	int nRead = write(GetFD(), pszBuf, uLen);
	if (-1 == nRead)
	{
		SetError(errno);
	}
#else
	int nRead = WriteFile(GetFD(), pszBuf, uLen);
	if (-1 == nRead)
	{
		SetError(GetLastError());
	}
}

